<template>
  <div class="page">
    <div class="topSearch">
      <div class="title">
        <span
          style="
            width: 3px;
            height: 20px;
            background-color: #0f79e2;
            margin-right: 8px;
          "
        ></span
        ><span>盘点列表</span>
      </div>
      <div class="search">
        <span>盘点单名：</span>
        <el-input
          size="small"
          clearable
          style="width: 250px"
          v-model="checkName"
          placeholder="请输入"
        ></el-input>
        <span>盘点类型：</span>
        <el-select size="small" v-model="checkType" clearable>
          <el-option value="1" label="动盘"></el-option>
          <el-option value="2" label="静盘"></el-option>
        </el-select>
        <span>仓库：</span>
        <el-select
          clearable
          v-model="areaId"
          size="small"
          style="width: 250px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
        <el-button
          size="small"
          type="primary"
          style="width: 80px; margin-left: 20px"
          @click="getCheckList"
          >查询
        </el-button>
        <el-button
          size="small"
          style="width: 80px; margin-left: 20px"
          @click="reset"
          >重置
        </el-button>
        <el-button
          size="small"
          type="primary"
          style="width: 100px; position: absolute; right: 40px"
          @click="addCheckList"
        >
          新增盘点单
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
        :data="checkData"
        border
        height="calc(100vh - 350px)"
        style="margin-top: 20px"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        v-loading="loading"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="checkId" label="单号" width="80px" />
        <el-table-column prop="checkName" label="单名" />
        <el-table-column prop="warehouse" label="仓库">
          <template slot-scope="scope">
            <div v-if="scope.row.areaId === 42">湖北仓</div>
            <div v-if="scope.row.areaId === 43">宁乡壹</div>
            <div v-if="scope.row.areaId === 44">广东仓</div>
            <div v-if="scope.row.areaId === 45">广西仓</div>
            <div v-if="scope.row.areaId === 52">贵州仓</div>
            <div v-if="scope.row.areaId === 53">云南仓</div>
            <div v-if="scope.row.areaId === 56">西安2仓</div>
            <div v-if="scope.row.areaId === 58">山西仓</div>
          </template>
        </el-table-column>
        <el-table-column label="盘点明细" width="500px">
          <template slot-scope="scope">
            <el-table
              :data="scope.row.checkDetailList"
              maxHeight="250px"
              :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
              :headerCellStyle="{
                textAlign: 'center',
                fontWeight: 400,
                background: '#66b1ff',
                color: 'white',
              }"
              border
              style="width: 100%"
            >
              <el-table-column prop="materialCode" label="材料编码" />
              <el-table-column
                prop="materialName"
                label="材料名称"
                width="150px"
              />
              <!--              <el-table-column prop="productName" label="产品" width="200px" />-->
              <el-table-column prop="price" label="成本价" />
              <el-table-column prop="checkCount" label="数量">
                <template slot-scope="scope">
                  <span v-if="scope.row.checkCount < 0" style="color: tomato">{{
                    scope.row.checkCount
                  }}</span>
                  <span
                    v-if="scope.row.checkCount > 0"
                    style="color: limegreen"
                    >{{ scope.row.checkCount }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column label="差价" prop="different" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="picture" label="凭证">
          <template slot-scope="scope">
            <el-image
              v-for="(v, i) in scope.row.checkVouchers"
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="sumXPrice" label="差价总计" />
        <el-table-column label="盘点状态">
          <template slot-scope="scope" width="60px">
            <span style="color: tomato" v-if="scope.row.sumXPrice < 0"
              >盘亏</span
            >
            <span style="color: #00bd01" v-if="scope.row.sumXPrice > 0"
              >盘盈</span
            >
          </template>
        </el-table-column>
<!--        <el-table-column prop="warehousePosition" label="库位" />-->
        <el-table-column label="盘点类型">
          <template slot-scope="scope">
            <span v-if="scope.row.checkType == 1">动盘</span>
            <span v-if="scope.row.checkType == 2">静盘</span>
          </template>
        </el-table-column>
        <el-table-column prop="placeOrderTime" label="动盘时间">
          <template slot-scope="scope">
            <div>{{ scope.row.startTime }}</div>
            <div>{{ scope.row.endTime }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="发起人" />
        <el-table-column prop="reason" label="备注" />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <span style="color: #00bd01" v-if="scope.row.checkStatus == 1"
              >通过</span
            >
            <span style="color: tomato" v-if="scope.row.checkStatus == 2"
              >驳回</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="userName == '赵凤娇'">
          <template slot-scope="scope">
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              @confirm="pass(scope.row, true)"
              icon-color="red"
              :title="`通过{` + scope.row.checkName + `}？`"
            >
              <el-link
                slot="reference"
                style="color: #0f79e2; cursor: pointer"
                v-if="scope.row.checkStatus == 0"
                >通过
              </el-link>
            </el-popconfirm>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              @confirm="pass(scope.row, false)"
              icon-color="red"
              :title="`驳回{` + scope.row.checkName + `}？`"
            >
              <el-link
                slot="reference"
                style="color: #ebb563; margin-left: 10px; cursor: pointer"
                v-if="scope.row.checkStatus == 0"
                >驳回
              </el-link>
            </el-popconfirm>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              @confirm="deleteCheck(scope.row)"
              icon-color="red"
              :title="`删除{` + scope.row.checkName + `}？`"
            >
              <el-link
                slot="reference"
                style="color: red; text-decoration: none; margin-right: 10px"
                v-if="scope.row.checkStatus == 2 || scope.row.checkStatus == 0"
                >删除
              </el-link>
            </el-popconfirm>
            <el-link
              @click="exportCheckList(scope.row)"
              style="color: #065aa4; text-decoration: none"
              >导出</el-link
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      style="padding: 20px 0"
      align="right"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[20, 30, 40, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
    >
    </el-pagination>
    <el-dialog
        :close-on-click-modal="false"
      title="新增盘点单"
      :visible.sync="addDialog"
      width="60%"
      center
        top="10px"
      :show-close="false"
      :before-close="handleClose"
    >
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>盘点单名：
        </div>
        <el-input
          size="small"
          v-model="addForm.checkName"
          style="width: 36%"
        ></el-input>
        <!--        <div style="width:80px;text-align: center;margin-left: 20px"><span style="color:red;">*</span>工厂：</div>-->
        <!--        <el-select clearable v-model="addForm.factoryId" size="small" style="width: 36%" @change="changeFactory"-->
        <!--                   placeholder="请选择工厂">-->
        <!--          <el-option v-for="item in factoryList" :key="item.factoryId" :label="item.factoryName"-->
        <!--                     :value='item.factoryId' />-->
        <!--        </el-select>-->
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>仓库：
        </div>
        <el-select
          clearable
          v-model="addForm.areaId"
          size="small"
          @change="getInventory"
          style="width: 36%"
          placeholder="请选择"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          />
        </el-select>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>盘点类型：
        </div>
        <el-select
          size="small"
          v-model="addForm.checkType"
          style="width: 36%"
          @change="changeOption"
        >
          <el-option value="1" label="动盘"></el-option>
          <el-option value="2" label="静盘"></el-option>
        </el-select>
      </div>
<!--        <div style="width: 80px; text-align: center" v-if="optionInven">-->
<!--          库位：-->
<!--        </div>-->
<!--        <el-input-->
<!--          size="small"-->
<!--          v-if="optionInven"-->
<!--          v-model="addForm.warehousePosition"-->
<!--          style="width: 36%"-->
<!--        ></el-input>-->
<!--      </div>-->
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">
          <span style="color: red">*</span>开始时间：
        </div>
        <el-date-picker
          v-model="addForm.startTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          style="width: 36%"
        >
        </el-date-picker>
        <div
          style="width: 80px; text-align: center; margin-left: 20px"
          v-if="optionInven"
        >
          <span style="color: red">*</span>结束时间：
        </div>
        <el-date-picker
          v-if="optionInven"
          v-model="addForm.endTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          style="width: 36%"
        >
        </el-date-picker>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 30px">
        <div style="width: 80px; text-align: center">备注：</div>
        <el-input
          size="small"
          type="textarea"
          v-model="addForm.reason"
          style="width: 36%"
        ></el-input>
      </div>
      <div style="display: flex; align-items: center; margin-bottom: 50px">
        <div style="width: 80px; text-align: center; margin-top: 30px">
          盘点凭证：
        </div>
        <div>
          <span style="color: gray; font-size: 12px"
            >(粘贴复制即可上传图片)</span
          >
          <div class="div" style="display: flex; align-items: center">
            <div
              v-for="(v, i) in preSalesImg"
              style="display: flex; align-items: center; margin-right: 10px"
            >
              <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
              >
              </el-image>
              <div @click="deletePic(i)">
                <el-icon name="delete"></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      分割线-->
      <el-table
        :data="factoryInventoryData"
        border
        max-height="300px"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        v-loading="loading"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="productCode" label="材料编码" width="100px" />
<!--        <el-table-column prop="warehousePosition" label="库位" width="100px" />-->
        <el-table-column prop="productName" label="材料名称" />
        <el-table-column prop="norms" label="规格" width="100px" />
        <el-table-column prop="colour" label="颜色" width="100px">
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100px" />
        <el-table-column prop="price" label="成本价" />
        <el-table-column prop="checkCount" label="数量">
          <template slot-scope="scope">
            <el-input-number
              :min="-200"
              :max="200"
              v-model="scope.row.checkCount"
              @change="countChange"
              size="small"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from 'axios';
import dayjs from 'dayjs';
import Decimal from 'decimal.js';
import * as XLSX from 'xlsx-js-style';
import store from "../../store";

export default {
  created () {
    let data = JSON.parse(window.localStorage.getItem('userData'));
    this.userName = data.userName
    document.addEventListener('paste', this.handlePaste)
    this.$api.areaLedgerAreaList().then(res => {
      this.warehouseList = res
    })
    this.$api.factoryGetFactoryList().then(res => {
      this.factoryList = res
    })
    this.getCheckList()
  },
  data () {
    return {
      checkName: "",
      checkId: "",
      areaId: "",
      warehouseList: [],
      factoryList: [],
      checkData: [],
      startTime: "",
      endTime: "",
      loading: false,
      addDialog: false,
      host: this.$imgHost,
      addForm: {},
      userName: "",
      factoryInventoryData: [],
      pageSize: 20,
      currentPage: 1,
      optionInven: false,
      checkType: "",
      preSalesImg: [],
      previewImg: [],
      totalCount: 0,
      preSalesImgList: [],
      pageNumber: 1
    }
  },
  methods: {
    handlePaste (event) {
      if (!this.addDialog) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage (imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token':store.state.token
        }
      })
        .then(response => {
          this.preSalesImg.push(response.data.result[0]);
          this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch(error => {
        });
    },
    //新增盘点单
    addCheckList () {
      this.addDialog = true
      this.preSalesImg = this.$options.data.call(this).preSalesImg
      this.addForm = this.$options.data.call(this).addForm
      this.factoryInventoryData = []
    },
    handleClose () {
    },
    changeFactory () {
    },
    getCheckList () {
      const params = {
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        checkName: this.checkName,
        checkType: this.checkType,
        areaId: this.areaId,
      }
      this.$api.checkCheckList(params).then(res => {
        res.data.forEach(el => {
          if (el.checkVouchers) {
            el.checkVouchers = [el.checkVouchers]
            el.checkVouchers.forEach(val => {
              this.previewImg.push('https://' + val)
            })
          }
          el.checkDetailList.forEach(val => {
            val.different = new Decimal(val.price).mul(val.checkCount).toNumber()
          })
        })
        this.checkData = res.data
        this.totalCount = res.total
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getCheckList()
    },
    handleCurrentChange (val) {
      this.pageNumber = val
      this.getCheckList()
    },
    reset () {
      this.checkType = ""
      this.areaId = ""
      this.checkName = ""
      this.getCheckList()
    },
    submit () {
      if (this.optionInven) {
        if (!this.addForm.checkName || !this.addForm.areaId || !this.addForm.checkType || !this.addForm.startTime || !this.addForm.endTime) {
          return this.$message({ message: "请检查必填项！" })
        }
      } else {
        if (!this.addForm.checkName || !this.addForm.areaId || !this.addForm.checkType || !this.addForm.startTime) {
          return this.$message({ message: "请检查必填项！" })
        }
      }

      const filteredList = this.factoryInventoryData.filter(item => item.checkCount !== 0); //采购数量必填，库位非必填
      const selectedFieldsArray = filteredList.map(product => ({
        materialCode: product.productCode,
        checkCount: product.checkCount,
        materialName: product.productName,
        price: product.price,
        // warehousePosition:product.warehousePosition,
        materialId: product.materialId,
      }));
      const data = {
        ...this.addForm,
        checkVouchers: this.preSalesImg.toString(),
        checkDetailList: selectedFieldsArray,
      }
      this.$api.checkCheckAdd(data).then(res => {
        this.$message({ message: "操作成功", type: "success" })
        this.addDialog = false
        this.getCheckList()
      })
    },
    getInventory (val) {
      this.$api.inventoryGetInventoryGoodsList({ areaId: val }).then(res => {
        res.forEach(el => {
          if (!el.checkCount) {
            el.checkCount = 0
          }
        })
        this.factoryInventoryData = res
      })
    },
    countChange (val) {
      console.log(val)
    },
    changeOption (val) {
      if (val == 1) {
        this.optionInven = true
      } else {
        this.optionInven = false
      }
    },
    pass (row, type) {
      const data = {
        type: type,
        checkId: row.checkId,
        checkDetailList: row.checkDetailList
      }
      this.$api.checkUpdateStatus(data).then(res => {
        this.$message({ message: "操作成功", type: 'success' })
        this.getCheckList()
      })
    },
    deleteCheck (row) {
      this.$api.checkCheckDelete({ checkId: row.checkId }).then(res => {
        this.$message({ message: "操作成功", type: 'success' })
        this.getCheckList()
      })
    },
    deletePic (i) {
      this.preSalesImg.splice(i, 1)
    },
    exportCheckList (row) {
      console.log(row)
      const wb = XLSX.utils.book_new();
      let data = []
      let warehouseName = ''
      if (row.areaId == 43) warehouseName = '宁乡壹';
      if (row.areaId == 44) warehouseName = '广东仓';
      if (row.areaId == 45) warehouseName = '广西仓';
      if (row.areaId == 52) warehouseName = '贵州仓';
      if (row.areaId == 53) warehouseName = '云南仓';
      if (row.areaId == 56) warehouseName = '西安2仓';
      if (row.areaId == 58) warehouseName = '山西仓';
      let typeName = ''
      if (row.checkType == 1) typeName = '动盘';
      if (row.checkType == 2) typeName = '静盘';
      let statusName = ''
      if (row.sumXPrice > 0) statusName = '盘盈';
      if (row.sumXPrice < 0) statusName = '盘亏';
      if (row.checkType == 1) {
        data = [
          [`${row.checkName + row.startTime + "-" + row.endTime}`, "", "", "", "", " ", ""],
          [`盘点类型:${typeName}`, '', `仓库:${warehouseName}`, ''],
          ['材料编码', '材料名称', '成本价', '数量', "差价"]]
        row.checkDetailList.map(el => {
          data.push([el.materialCode, el.materialName, el.price, el.checkCount, el.different]);
        })
      } else {
        data = [
          [`${row.checkName + row.startTime}`, "", "", "", "", " ",],
          [`盘点类型:${typeName}`, '', `仓库:${warehouseName}`, ''],
          ['材料编码', '材料名称', '成本价', '数量', "差价"]]
        row.checkDetailList.map(el => {
          data.push([el.materialCode, el.materialName, el.price, el.checkCount, el.different]);
        })
      }
      data.push(["", "", "", "差价总计", `${row.sumXPrice}`])
      data.push(["", "", "", "盘点状态", `${statusName}`])
      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = [
        { wpx: 100 }, // 第一列宽度为250单位
        { wpx: 200 }, // 第二列宽度为300单位
        { wpx: 100 },  // 第三列宽度为350单位
        { wpx: 100 },
        { wpx: 100 },
        { wpx: 100 },
      ];
      const range = XLSX.utils.decode_range(ws['!ref']);
      const totalRows = range.e.r + 1; // 行数从 0 开始，所以需要 +1
      // 定义红色的样式
      const redFontStyle = {
        font: { color: { rgb: "ff0000" } },// 红色的 RGB 代码
      };
      const centerAlignStyle = {
        alignment: {
          horizontal: "center",
          vertical: "center"
        }
      }
      // 应用样式到所有单元格
      for (let R = 0; R < data.length; R++) {
        for (let C = 0; C < data[R].length; C++) {
          const cell_address = XLSX.utils.encode_cell({ r: R, c: C });
          ws[cell_address].s = centerAlignStyle;
        }
      }
      // 将样式应用到最后两行
      for (let row = totalRows - 2; row < totalRows; row++) {
        for (let col = range.s.c; col <= range.e.c; col++) {
          const cellAddress = { c: col, r: row };
          const cellRef = XLSX.utils.encode_cell(cellAddress);
          if (!ws[cellRef]) ws[cellRef] = {}; // 确保单元格存在
          ws[cellRef].s = redFontStyle; // 应用红色字体样式
        }
      }
      ws["A1"].s = {
        alignment: { horizontal: 'center' },
        font: { blod: true, color: { rgb: '000000' } },
        fill: { fgColor: { rgb: 'E3F2FD' } }
      }
      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
      ws['!merges'] = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 4 } },  // 合并第一行的 A 列到 H 列
        { s: { r: 1, c: 0 }, e: { r: 1, c: 1 } }, // 合并第二行的 A 列到 B 列
        { s: { r: 1, c: 2 }, e: { r: 1, c: 4 } }  // 合并第二行的 C 列到 E 列
      ];
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
      // 创建一个 Blob 对象
      const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      // 使用 Blob 对象创建一个链接
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `${row.checkName}${new Date().getTime()}.xlsx`;
      // 触发下载
      link.click();
      // 清理
      URL.revokeObjectURL(link.href);

      function s2ab (s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    }
  }
}
</script>
<style lang='less' scoped>
.title {
  display: flex;
  margin-left: 20px;

  span {
    display: flex;
    margin-top: 20px;
  }
}

.topSearch {
  width: 100%;
  height: 110px;
  box-shadow: inset 0 20px 10px rgba(0, 128, 255, 0.2);
  border-bottom: 1px solid rgba(0, 128, 255, 0.08);

  .search {
    display: flex;
    align-items: center;
    margin-top: 15px;

    span {
      margin-left: 20px;
    }
  }
}
</style>
